package com.ych.service.impl;

import com.ych.beans.Message;
import com.ych.beans.Perm;
import com.ych.beans.Role;
import com.ych.dao.PermDao;
import com.ych.dao.RoleDao;
import com.ych.service.PermService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class PermServiceImpl implements PermService {
    @Autowired
    PermDao dao;

    @Autowired
    RoleDao roleDao;

    @Override
    public Message selectPerms() {
        final Message message = new Message();
        List<Perm> list = dao.selectPerms();
        message.setSuccess(true);
        message.setObj(list);
        return message;
    }

    @Override
    public Message addPermForRole(Integer role_id, Integer perm_id) {
        Message message = new Message();
        Role role = new Role();
        boolean hasThisPerm = false;
        boolean addSuccess = false;

        List<Role> roles = roleDao.selectRole(null, role_id);
        if (!roles.isEmpty()){
            role = roles.get(0);
        }
        List<Perm> perms = role.getPerms();

        //判断role中是否存在该perm，避免重复添加
        for (Perm perm : perms) {
            if (perm.getId() == perm_id){
                hasThisPerm = true;
                break;
            }
        }
        if (!hasThisPerm){
            dao.addPermForRole(role_id,perm_id);
            addSuccess = true;
        }
        message.setSuccess(addSuccess);
        if (addSuccess){
            message.setMsg("给角色添加权限成功");
        }else {
            message.setMsg("添加失败");
        }
        return message;
    }
}
